
package com.eclub.emotion.rootstone.server.deploy.bytecode;

import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;

import com.eclub.emotion.rootstone.server.context.IProxyFactory;
import com.eclub.emotion.rootstone.server.deploy.DynamicClassLoader;


/**
 * 
 * @author Service Platform Architecture Team (spat@58.com)
 */
public class CreateManager {
	
	private static Logger logger = Logger.getLogger(CreateManager.class);

	public IProxyFactory careteProxy(String serviceRootPath, DynamicClassLoader classLoader) throws Exception {
		
		String configPath = serviceRootPath + "/" + Constant.SERVICE_CONTRACT;
		File file = new File(configPath);
		ContractInfo serviceContract = null;
		
		serviceContract = ContractConfig.loadContractInfo(configPath, classLoader);
		
		
		long time = System.currentTimeMillis();
		List<ClassFile> localProxyList = new ProxyClassCreater().createProxy(classLoader, serviceContract, time);
		ClassFile cfProxyFactory = new ProxyFactoryCreater().createProxy(classLoader, serviceContract, time);
		
		List<IProxyStub> localProxyAry = new ArrayList<IProxyStub>();
		for(ClassFile cf : localProxyList) {
			Class<?> cls = classLoader.findClass(cf.getClsName(), cf.getClsByte(), null);
			logger.info("dynamic load class:" + cls.getName());
			localProxyAry.add((IProxyStub)cls.newInstance());
		}
		
		Class<?> proxyFactoryCls = classLoader.findClass(cfProxyFactory.getClsName(), cfProxyFactory.getClsByte(), null);
		Constructor<?> constructor = proxyFactoryCls.getConstructor(List.class);
		IProxyFactory pfInstance = (IProxyFactory)constructor.newInstance(localProxyAry);
		logger.info("crate ProxyFactory instance!!!");
		return pfInstance;
	}
}